package qsh.laputa.controller;


import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import qsh.laputa.entity.Customer;
import qsh.laputa.service.CustomerService;
import qsh.laputa.util.MyQuery;
import qsh.laputa.util.QueryUtil;
import qsh.laputa.util.ResultUtil;

import java.util.Map;

/**
 * <p>
 * 客户表 前端控制器
 * </p>
 *
 * @author Qsh
 * @since 2021-02-22
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    /**
     * 进入列表页
     *
     * @return
     */
    @GetMapping("toList")
    public String toList() {
        return "customer/customerList";
    }

    /**
     * 查询
     *
     * @return
     */
    @ResponseBody
    @GetMapping("list")
    public R<Map<String, Object>> list(@RequestParam Map<String, String> params) {
        MyQuery<Customer> myQuery = QueryUtil.buildMyQuery(params);

        Page<Customer> myPage = customerService.page(myQuery.getPage(),
                myQuery.getWrapper().orderByDesc("customer_id"));

        return ResultUtil.buildPageR(myPage);
    }

    /**
     * 进入新增页
     *
     * @return
     */
    @GetMapping("toAdd")
    public String toAdd() {
        return "customer/customerAdd";
    }

    /**
     * 新增客户
     *
     * @param customer
     * @return
     */
    @ResponseBody
    @PostMapping("add")
    public R<Object> add(@RequestBody Customer customer) {
        return ResultUtil.buildR(customerService.save(customer));
    }

    /**
     * 进入修改页
     *
     * @return
     */
    @GetMapping("toUpdate/{id}")
    public String toUpdate(@PathVariable Long id, Model model) {
        Customer customer = customerService.getById(id);
        model.addAttribute("customer", customer);   //将对象储存在 Model 对象中
        return "customer/customerUpdate";
    }

    /**
     * 修改客户
     *
     * @param customer
     * @return
     */
    @ResponseBody
    @PutMapping("update")
    public R<Object> update(@RequestBody Customer customer) {
        return ResultUtil.buildR(customerService.updateById(customer));
    }

    /**
     * 删除客户
     *
     * @return
     */
    @ResponseBody
    @DeleteMapping("toDelete/{id}")
    public R<Object> toDelete(@PathVariable Long id) {
        Customer customer = new Customer();
        customer.setCustomerId(id);

        return ResultUtil.buildR(customerService.removeByIdWithFill(customer));
    }

    /**
     * 进入详情页
     *
     * @return
     */
    @GetMapping("toDetail/{id}")
    public String toDetail(@PathVariable Long id, Model model) {
        Customer customer = customerService.getById(id);
        model.addAttribute("customer", customer);   //将对象储存在 Model 对象中
        return "customer/customerDetail";
    }

}
